// *******************************************************************************************************
// # エリア
//   ・検索結果 リスト
// *******************************************************************************************************

var ResultBridge = ResultBridge || {};

var PageMove;
var ReSearch;
var ReSearchEki;
var ResearchCity;
var ShowType;
var PrepareParameter;
var flg = true;

	function forie8changeFormDesign () {

		var cnt1, cnt2;

		$(document).on('click','#contentSubColumn .list_btn_action a', function() {


			$('#modal_result_area .mod_ttl_bar').each(function(i) {
				var val = $(this).find('input').prop("checked");

				if (val != false) {
					$(this).addClass('mod_checked');
				}

			});

			$('#modal_result_station .list_search li').each(function(i) {
				var val = $(this).find('input').prop("checked");

				if (val != false) {
					$(this).addClass('mod_checked');
				}

			});
				cnt2 = $('#modal_result_station .list_search li.mod_checked').length;
			if (cnt2 > 0) {
				$('#modal_result_station .mod_btn_append a').addClass('mod_btn_all_pink');
				$('#modal_result_station .mod_btn_append a').removeClass('mod_btn_disabled');
			} else {
				$('#modal_result_station .mod_btn_append a').removeClass('mod_btn_all_pink');
				$('#modal_result_station .mod_btn_append a').addClass('mod_btn_disabled');
			}

			$('#modal_result_area .list_search li').each(function(i) {
				var val = $(this).find('input').prop("checked");

				if (val != false) {
					$(this).addClass('mod_checked');
				}


			});
				cnt1 = $('#modal_result_area .list_search li.mod_checked').length;
			if (cnt1 > 0) {
				$('#modal_result_area .mod_btn_append a').addClass('mod_btn_all_pink');
				$('#modal_result_area .mod_btn_append a').removeClass('mod_btn_disabled');
			} else {
				$('#modal_result_area .mod_btn_append a').removeClass('mod_btn_all_pink');
				$('#modal_result_area .mod_btn_append a').addClass('mod_btn_disabled');
			}

		});

		$(document).on('click', '#modal_result_area .mod_ttl_bar input', function() {

			if ($(this).closest('.mod_ttl_bar').hasClass('mod_checked') > 0) {
				$(this).closest('.mod_ttl_bar').removeClass('mod_checked');
				$(this).closest('.mod_ttl_bar').next().find('li').removeClass('mod_checked').find('input').prop({'checked':false});

			} else {
				$(this).closest('.mod_ttl_bar').addClass('mod_checked');
				$(this).closest('.mod_ttl_bar').next().find('li').addClass('mod_checked').find('input').prop({'checked':'checked'});

			}

			checkCount();

		});


		$(document).on('click','#modal_result_area .list_search li input, #modal_result_station .list_search li input', function() {

			if ($(this).closest('.mod_check').hasClass('mod_checked') > 0) {
				$(this).closest('.mod_check').removeClass('mod_checked');
				$(this).closest('.list_search').prev().removeClass('mod_checked').find('input').prop({'checked':false});
			} else {
				$(this).closest('.mod_check').addClass('mod_checked');
			}

			checkCount();

		});

		function checkCount() {
			var cnt1 = $('#modal_result_area .list_search li.mod_checked').length;
			if (cnt1 > 0) {
				$('#modal_result_area .mod_btn_append a').addClass('mod_btn_all_pink');
				$('#modal_result_area .mod_btn_append a').removeClass('mod_btn_disabled');
			} else {
				$('#modal_result_area .mod_btn_append a').removeClass('mod_btn_all_pink');
				$('#modal_result_area .mod_btn_append a').addClass('mod_btn_disabled');
			}

			var cnt2 = $('#modal_result_station .list_search li.mod_checked').length;
			if (cnt2 > 0) {
				$('#modal_result_station .mod_btn_append a').addClass('mod_btn_all_pink');
				$('#modal_result_station .mod_btn_append a').removeClass('mod_btn_disabled');
			} else {
				$('#modal_result_station .mod_btn_append a').removeClass('mod_btn_all_pink');
				$('#modal_result_station .mod_btn_append a').addClass('mod_btn_disabled');
			}

		}
	}


$(function() {

	var ua = navigator.userAgent;
	if(ua.indexOf('MSIE 8') != -1){ 
		forie8changeFormDesign();
	} 

	var isUnderIe6 = uaInfo.isIe && uaInfo.ieVr <= 6,
		isUnderIe7 = uaInfo.isIe && uaInfo.ieVr <= 7, 
		useIcheck  = !(uaInfo.isIe && uaInfo.ieVr <= 8)


	/*******************************************************
	 *　tooltip
	 *******************************************************/
	$('.tooltip').powerTip({
		placement: isUnderIe6 ? 'e' : 'n'
	});
	$('.tooltip.zoom').each(function(i){
		$(this).data('powertiptarget', $(this).next().attr('id'));
	});

	/*******************************************************
	 * 検証リストに追加
	 *******************************************************/
	
	$('#contentMainColumn .mod_box_section_bdt .mod_table').find('a.mod_icn_star').on('click', function(e){
		e.preventDefault();
		if (!$(this).hasClass('mod_icn_star_active')) {
			$(this).addClass('mod_icn_star_active');
			addStar.show();
			//検討リスクに追加
			KENTO.addKentoList($(this).prev().val());
		};
	});
	
	$('#contentMainColumn .wrapper_picture').find('a.mod_icn_star').on('click', function(e){
		e.preventDefault();
		if (!$(this).hasClass('mod_icn_star_active')) {
			$(this).addClass('mod_icn_star_active');
			addStar.show();
			//検討リスクに追加
			KENTO.addKentoList($(this).prev().val());
		};
	});
	
	var addStar = new APMN.ModalStar({
		path: '/static/shared/images/img_add_star.png',
		ieVr: !(isUnderIe6)
	});
	
	//画像ビューのサイズ
	/*
	window.setTimeout(function(){
		var listtype = $('#listtype').val();
		if(listtype != '1') return;
		$('.mod_box_section_bdt').each(function(index){
			if(index % 2 == 0){
				var me = $(this);
				var next = $(this).next();
				if(me.height() < next.height()){
					me.height(next.height());
				}
				else if(me.height() > next.height()){
					next.height(me.height());
				}
			}
		});
		appendWrapper.changeCtsHeight();
		//$('#appendContainerWrapper').removeAttr('style');
	}, 2000);
	*/
	
	/*******************************************************
	 * まとめてお問い合わせ
	 *******************************************************/
	var isSelected = false,
		SelectMax = 20;

	$('.mod_table.mod_table_col').find('tr').each(function(i){
		var $self = $(this);
		if (useIcheck) {
			$self.find('input')
				.on('ifChecked', function(e){
					changeCheckBox();
				})
				.on('ifUnchecked', function(e){
					changeCheckBox();
				});
		} else {
			$self.find('input')
				.on('click', function(e){
					changeCheckBox();
				});
		};
	});

	function changeCheckBox(){
		
		var _isSlt = false;
		$('.mod_table.mod_table_col .mod_check').each(function(e){
			if ($(this).find('input').prop('checked')) {
				_isSlt = true;
				return false;
			};
		});
		if (isSelected != _isSlt) {
			isSelected = _isSlt;
			if (isSelected) {
				changeInquiryBtn(true);
			} else {
				changeInquiryBtn(false);
			}
		};
	};
	
	//★★★リストビュー
	var val = $('#listtype').val();
	if(val == '' || val == '1'){
		changeCheckBox();
	}
	//★★★リストビュー

	var $allBtnUdr = $('.mod_box_section.box_pager .button a'),
		$allBtnWrp = $('.mod_btn_append a');

	$allBtnUdr.on('click', function(e){
		var _n = checkInquiryIsOver();
		if (_n < 0) {
			e.preventDefault();
			if (_n == -1) {
				modalOverSelect.show();
			};
		};
	});
	$allBtnWrp.on('click', function(e){
		var _n = checkInquiryIsOver();
		if (_n < 0) {
			e.preventDefault();
			if (_n == -1) {
				modalOverSelect.show();
			};
		};
	});

	function changeInquiryBtn(b) {
		if (b) {
			if($allBtnUdr != undefined) $allBtnUdr.removeClass('mod_btn_disabled');
			if($allBtnWrp != undefined) $allBtnWrp.removeClass('mod_btn_disabled');
		} else {
			if($allBtnUdr != undefined) $allBtnUdr.addClass('mod_btn_disabled');
			if($allBtnWrp != undefined) $allBtnWrp.addClass('mod_btn_disabled');
		};
	};

	function checkInquiryIsOver(){
		if (isSelected) {
			var _num = 0;
			$('.mod_table.mod_table_col .mod_check').each(function(i){
				if ($(this).find('input').prop('checked')) {
					_num++;
				};
			});
			if (SelectMax < _num) return -1;
			else return 1;
		};
		return -2;
	};

	var modalOverSelect = new APMN.Modal({
		target: $('#modal_gomen'),
		close: $('#modal_gomen .modal_close'),
		ieVr: !(isUnderIe6)
	});

	function submit(action, method, values) {
 	   var form = $('<form/>', {
	        action: action,
	        method: method
	    });
	    $.each(values, function() {
	        form.append($('<input/>', {
	            type: 'hidden',
	            name: this.name,
	            value: this.value
	        }));    
	    });
	    form.appendTo('body').submit();
	}
	
	//Submitのパラメータ準備
	function prepareParameter(){
		var items=[];
		var typ = $('input[name="search_type"]').attr("value");
		var listtype = $('#listtype').val();
		items.push({name:'search_type',value:typ});
		items.push({name:'listtype',value:listtype});
		
		//マップ用
		var maptarget = $('#maptarget').val();
		if(maptarget != undefined){
			items.push({name:'maptarget',value:maptarget});
		}

		var pos = 0;
		$('.search_target').each(function(index){
			if($(this).attr("id") != undefined && $(this).attr("id") != "undefined" && $(this).attr("id") != ""){
				items.push({name:'target_'+pos, value:$(this).attr("id")});
				pos++;
			}				
		});
		
		//町名検索
		$('li[name=search_targetChou]').each(function(index){
			items.push({name:'targetchou_'+index, value:$(this).attr("id")});			
		});

		//グループ
		if($('#madoriGroupCheck').prop('checked')){
			var firstIndex = -1;
			var firstMadori = $('#madoriGroup').val();			
			$('input[type=checkbox][name^=madori][id^=madori]').each(function(index){
				if($(this).val() == firstMadori){
					firstIndex = index;					
				}	
				if(firstIndex > -1 && index >= firstIndex){
					if (useIcheck) {
						$(this).iCheck('check');
					}
					else {
						$(this).prop('checked', true);
					}
				}
			});			
		}
		//グループ
		
		var campaignIndex = 0;
		$('input:checked').each(function(index){
			var elem = $(this);
			var val = elem.attr("value");
			if(elem.attr('name').indexOf('madori') == 0){
				val = 'on';
			}
			if(elem.attr("name") != ""){
				items.push({name:elem.attr("name"), value:val});
				/*
				if(elem.attr("name").indexOf('campaign') >= 0){
					items.push({name:elem.attr("name") + '[' + campaignIndex + ']', value:val});
					campaignIndex++;
				}
				else {
					items.push({name:elem.attr("name"), value:val});
				}
				*/				
			}			
		});

		$('select').each(function(index){
			var elem = $(this);
			if(elem.attr("name") != ""){
				items.push({name:elem.attr("name"), value:elem.find("option:selected").attr("value")});
			}			
		});

		items.push({name:'page',value:1});
		
		return items;
	}
	PrepareParameter = prepareParameter;
	
	//再検索メソッド
	function go(page) {
		
		
		//★★★検索する前家賃と間取り条件をCookieに保存する		
		var tinryo1 = $('select[name=tinryo1]').first().val();
		var tinryo2 = $('select[name=tinryo2]').first().val();
		if(tinryo2 == '9999999') tinryo2 = '0'
		var madori = [];
		$('input[name^=madori]:checked').each(function(){
			madori.push($(this).attr('name'));
		});
		var cons = "tinryo1:" + tinryo1 + "|tinryo2:" + tinryo2 + "|madori:" + madori.join();
		$.cookie.defaults = { path: '/' }; 
		$.cookie('SAVE_CONS', cons);
		
		//★★★検索する前家賃と間取り条件をCookieに保存する
				
		var items = prepareParameter();
		//マップビュー
		items.push({name:'maptarget', value:$('#maptarget').val()});
		
		submit('/rstobi/rstobi','POST',items);
	}
	ReSearch = go;
	
	//3つの間取りこだわり条件と一般こだわり条件
	function customKodawari(){
		
		//メゾネット
		if($('input[name=kodawari77]:checked').length > 0){
			$('input[name=kodawari77]').each(function(){
				$(this).attr('checked', true);
				$(this).parent().addClass('checked');
			});
		}
		//ロフト
		if($('input[name=kodawari62]:checked').length > 0){
			$('input[name=kodawari62]').each(function(){
				$(this).attr('checked', true);
				$(this).parent().addClass('checked');
			});
		}
		//2階以上
		if($('input[name=kodawari5]:checked').length > 0){
			$('input[name=kodawari5]').each(function(){
				$(this).attr('checked', true);
				$(this).parent().addClass('checked');
			});
		}		
		
		//イベント
		if (useIcheck) {
			//メゾネット
			$('input[name=kodawari77],input[name=kodawari62],input[name=kodawari5]').on('ifChecked', function(e){
				var name = $(this).attr('name');
				$('input[name=' + name + ']').each(function(){						
					$(this).prop('checked', true);
					$(this).parent().addClass('checked');
				});	
			})
			.on('ifUnchecked', function(e){		
				var name = $(this).attr('name');
				$('input[name=' + name + ']').each(function(){						
					$(this).prop('checked', false);
					$(this).parent().removeClass('checked');
				});	
			});
		}
		else {
			$('input[name=kodawari77],input[name=kodawari62],input[name=kodawari5]').on('click', function(e){	
				var name = $(this).attr('name');
				if(!$(this).prop('checked')){					
					$('input[name=' + name + ']').each(function(){
						$(this).prop('checked', false);
						$(this).parent().removeClass('checked');
					});						
				}
				else{
					$('input[name=' + name + ']').each(function(){
						$(this).prop('checked', true);
						$(this).parent().addClass('checked');
					});
				}
			});
		};
	}
	customKodawari();	
		
	
	//ページング
	function go2(page) {
		var items=[];
		//var form = document.forms[0];
		//for (var i=0; i<form.length; i++){
		$('[name^=this_params]').each(function(){			
			var name = $(this).attr('name');
			//alert(name);
			var value = $(this).val();
			if (name == "this_params[page]") {
				// skip
			} 
			else if (name.substr(0,11) == "this_params") {
				
				if (name.match(/^this_params\[(.+)\]\[(.+)\]$/, "$1[$2]")) {
					items.push({name:name.replace(/^this_params\[(.+)\]\[(.+)\]$/, "$1[$2]"),value:value});
				} 
				else if (name.match(/^this_params\[(.+)\]$/, "$1")) {
					items.push({name:name.replace(/^this_params\[(.+)\]$/, "$1"),value:value});
				}
			}
		});
		items.push({name:'page',value:page||1});
		//console.dir(items);
		submit('/rstobi/rstobi','POST',items);
	}
	PageMove = go2;
	
	//駅変更して、再検索
	function go3(){
		
		var sel = true;
		var target = $('#modal_result_station').find('.mod_btn_all');
		sel = !target.hasClass('mod_btn_disabled');
		if(!sel) return;
		
		$('#modal_result_station').hide();
		//過去のデータを削除
		$(".list_arealine").each(function(){
			$(this).empty();
		});
		
		var ekis = [];
		$('#modal_result_station').find('.mod_checked').each(function(e){
			ekis.push({id:$(this).attr('id'), name:$(this).find('.name').html()});
			//alert($(this).attr('id'));
			//var $li = '<li class="search_target" id="' + $(this).attr('id') + '">' + $(this).find('.name').html() + '</li>';
			//$('.list_arealine').first().append($li);						
		});
		
		var sorted = ekis.sort(function(a, b) {
		  return a.id - b.id;
		});
		for(var i = 0 ; i < sorted.length; i++){
			var $li = '<li class="search_target" id="' + sorted[i].id + '">' + sorted[i].name + '</li>';
			$('.list_arealine').first().append($li);
		}
		
		go(1);
	}
	ReSearchEki = go3;
	
	//市区町村再検索
	function gocity(){			
		//過去のデータを削除
		var sel = true;
		var target = $('#modal_result_area').find('.mod_btn_all');
		sel = !target.hasClass('mod_btn_disabled');
		if(!sel) return;
		
		$(".search_target").each(function(){
			$(this).remove();
		});
		$(".search_targetChou").each(function(){
			$(this).remove();
		});				
		$('#areaBlock').empty();
		
		$('#modal_result_area').find('.mod_checked').each(function(e){
			var $li = '<li class="search_target" id="' + $(this).attr('id') + '">' + $(this).find('.name').html() + '</li>';			
			$('#areaBlock').append($li);						
		});
		$('#modal_result_area').hide();	
		ReSearch(1);
	}
	ReSearchCity = gocity;
	//市区町村再検索
	
	//表示仕方変えるメソッド
	function go4(type, maptarget){
		$('#listtype').val(type);

		//マップビュー
		if(maptarget != undefined){
			$('#maptarget').val(maptarget);
		}
		go(1);
	}
	ShowType = go4;
	
	//町名選択クリック
	$('#lnkTownLink').click(function(){
		var items = prepareParameter();
		//console.dir(items);
		submit('/area/town/','POST',items);
	});
	
	/*******************************************************
	 * SEO詳細開閉
	 *******************************************************/
	function seoSetting(){
		var SeoOpener = (function(obj){
			var that = {
				isOpen: false,
				isMove: false,
				timer: null,
				$btn: '',
				$target: '',
				hAll: 0,
				hCt2: 0
			};
			function init(obj){
				that.$btn = obj.btn;
				that.$target = obj.target;
				that.hAll = that.$target.height();
				that.hCt2 = that.$target.find('li').eq(0).outerHeight(true) * obj.lin;
				if (that.hAll > that.hCt2) {
					that.$btn.on('click', function(e){
						e.preventDefault();
						if (that.isMove) return;
						that.isMove = true;
						that.isOpen = !that.isOpen;
						changeStart();
						changeMoving();
						var _pt = that.isOpen ? that.hAll : that.hCt2;
						that.$target.stop().animate({ 'height': _pt }, 400, 'easeOutQuart', function(e){
							changeEnd();
						});
					});
					that.$target.css({
						'height':that.hCt2
					});
					changeStart();
				} else {
					that.$btn.hide();
				};
			};
			function changeStart(){
				if (that.isOpen) {
					that.$btn.find('a').text('-閉じる');
				} else {
					that.$btn.find('a').text('+すべて表示');
				};
			};
			function changeMoving(){
				clearInterval(that.timer);
				that.timer = setInterval(function(e){
					ResultBridge.appendChange();
				}, 1000/60);
			};
			function changeEnd(){
				clearInterval(that.timer);
				that.isMove = false;
			};
			init(obj);
			return that;
		});

		$('#contentMainColumn .mod_box_authority_btm').each(function(i){
			if ($(this).hasClass('area') || $(this).hasClass('station')) {
				var opener = new SeoOpener({
					btn: $(this).find('.btn_showall'),
					target: $(this).find('.list_authority'),
					lin: $(this).hasClass('area') ? 2 : 4
				});
			};
		});
	};
	seoSetting();
	
	var appendWrapper = new APMN.AppendWrapper({
		isFixed: true,
		ieVr: !(isUnderIe6)
	});
	
	
});
